package com.smasher.dialog.select.delegate

import android.util.Log
import okhttp3.MediaType.Companion.toMediaType
import okhttp3.RequestBody
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONArray
import org.json.JSONObject

open class DefaultQueryDelegate {

    open val sortField: String = "Id"
    open val sortType: String = SORT_TYPE_ASC
    open val condition: String = "CustomerName"
    open val filterType: String = FILTER_TYPE_CONTAINS

    open fun createParam(key: String, pageNumber: Int): RequestBody {
        val search = createSearch(key)
        val json = JSONObject().apply {
            put("PageIndex", pageNumber)
            put("PageRows", 10)
            put("SortField", sortField)
            put("SortType", sortType)
            put("Search", search)
        }
        Log.e(TAG, "queryNet: $json")
        return json.toString().toRequestBody("application/json; charset=utf-8".toMediaType())
    }

    open fun createSearch(key: String): JSONObject? {
        if (key.isNotEmpty()) {
            val conditions = JSONArray().apply {
                put(condition)
            }
            val filterTypes = JSONArray().apply {
                put(filterType)
            }
            val keywords = JSONArray().apply {
                put(key)
            }
            return JSONObject().apply {
                put("Conditions", conditions)
                put("FilterTypes", filterTypes)
                put("Keywords", keywords)
            }
        }
        return null
    }

    companion object {
        const val TAG = ""
        const val SORT_TYPE_ASC = "asc"
        const val SORT_TYPE_DESC = "desc"
        const val FILTER_TYPE_CONTAINS = "Contains"
        const val FILTER_TYPE_EQUALS = "Equals"
    }

}